<?php

namespace App\Http\Controllers;

use App\Common\ErrorMsg;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Input;

/**
 * @SWG\Swagger(
 *   @SWG\Info(
 *     title="wenjoying.com Api",
 *     version="2.0.0",
 *     description="wenjoying.com Api",
 *     @SWG\Contact(
 *         email="wenjoying@126.com"
 *     )
 *   )
 * )
 * @SWG\SecurityScheme(
 *     securityDefinition="Bearer",
 *     type="apiKey",
 *     in="header",
 *     name="Authorization"
 * )
 **/
class Controller extends BaseController
{
    /**
     * 测试方法
     * @param $params
     * @return string
     */
    public function index($params)
    {
        return 'welcome test';
    }

    /**
     * 获取输入参数
     * @param string $key 参数名称
     * @param string $value 默认值
     * @return array
     */
    protected function input($key, $value = null)
    {
        $value = Input::get($key, $value);
        if (isset($value)) {
            clean_xss($value, true);
        }
        return $value;
    }

    /**
     * Ajax方式返回数据到客户端
     * @param int $code
     * @param string $msg
     * @param string $data
     * @param string $type
     * @return array|\Illuminate\Http\JsonResponse
     */
    protected function ajaxReturn($code = 0, $msg = '', $data = '', $type = 'JSON')
    {
        $error_msg   = ErrorMsg::get_msg($code) . (empty($msg) ? '' : '：' . $msg);
        $return_data = [
            'code' => $code,
            'msg'  => $error_msg,
            'data' => $data === '' ? (object)null : $data
        ];

        header('Content-Type:text/html; charset=utf-8');

        switch (strtoupper($type)) {
            case 'JSON' :
                $origin = request()->header("Origin");
                header("Access-Control-Allow-Origin: {$origin}"); # 允许任意域名发起的跨域请求
                header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With');
                header("Access-Control-Allow-Credentials: true");
                return response()->json($return_data, 200, [], JSON_UNESCAPED_UNICODE);

            case 'XML'  :
                return (xml_encode($return_data));

            case 'JSONP':
                return response()->json($return_data, 200, [], JSON_UNESCAPED_UNICODE)->withCallback($this->input('callback'));

            case 'EVAL' :
                return ($return_data);
        }
        die();
    }


}